<?php

include_once 'admin.php';

/**
 *马拉松活动
 */
class actMarathonController extends adminController
{
    public function __construct() {
        parent::__construct();
    }
    
    /**
     * 活动添加编辑页
     */
    public function domarathonInfo() {
        $mapAttr = $routeAttr = $coordinate
                 = $mileRule  = $rankRule
                 = $timeRule  = $marathon_img
                 = $rowData   = null;
        $canEdit = true;
        
        if ($mid = common::request('m_id', 'G')) {
            $rowData    = $this->db->getRowTable('r_activity_marathon', [], 'id=' . $mid);
            $nTime      = time();
            
            if ($nTime > $rowData['start_time'] && $nTime < $rowData['end_time'] || $rowData['status'] == 1) { //活动进行中，禁止编辑
                $canEdit = false;
            }
            
            $mapAttr        = $rowData['mapattr'];
            $routeAttr      = json_decode($rowData['routeattr'], true);
            $coordinate     = $rowData['coordinate'] ? gzuncompress($rowData['coordinate']) : '';
            $marathon_img   = json_decode($rowData['marathon_img'], true);
            $prompt_rule    = json_decode($rowData['prompt_rule'], true);
        
            $mileRule       = !empty($prompt_rule['mileage']) ? implode(',', array_values($prompt_rule['mileage'])) : '';
            $rankRule       = !empty($prompt_rule['rank']) ? implode(',', array_values($prompt_rule['rank'])) : '';
            $timeRule       = !empty($prompt_rule['elapsedtime']) ? implode(',', array_values($prompt_rule['elapsedtime'])) : '';
            unset($rowData['mapattr'], $rowData['routeattr'], $rowData['coordinate'], $rowData['marathon_img'], $rowData['prompt_rule']);           
        } 
        
        $this->view->assign('canEdit', $canEdit);
        $this->view->assign('mapAttr', $mapAttr);
        $this->view->assign('routeAttr', $routeAttr);
        $this->view->assign('coordinate', $coordinate);
        $this->view->assign('mileRule', $mileRule);
        $this->view->assign('rankRule', $rankRule);
        $this->view->assign('timeRule', $timeRule);
        $this->view->assign('marathon_img', $marathon_img); 
        $this->view->assign('mInfos', $rowData);
        
        $this->view->display('marathoninfo');
    }
    
    /**
     * 插入或更新马拉松活动
     */
    public function domarathonAddEdit() {
        $marathonId     = common::request('marathonId', 'P');
        $points         = common::request('clickPoint', 'P');
        $title          = common::request('title', 'P');
        $introduce      = common::request('introduce', 'P');
//        $charge         = common::request('charge', 'P');
        $total_mileage  = common::request('mileage', 'P');
        $start_time     = strtotime(common::request('starttime', 'P'));
        $end_time       = strtotime(common::request('endtime', 'P'));
		$ruleMiletype	= common::request('rule-miletype', 'P');
        $ruleRanktype	= common::request('rule-ranktype', 'P');
        $ruleTimetype	= common::request('rule-timetype', 'P');
		$copycontent	= common::request('copycontent', 'P');
        $initial_joins	= common::request('initial_joins', 'P');
        $mapattr        = $points ? json_encode([
            'zoom'      => common::request('mapZoom', 'P'),
            'center'    => common::request('mapCenter', 'P')
        ]) : null;
        common::request('mapAttr', 'P') && $mapattr = common::request('mapAttr', 'P');
        $routeattr      = json_encode([
            'lineAttr'      => common::request('lineAttr', 'P'),
            'runLineAttr'   => common::request('runLineAttr', 'P')
        ]); 
        $coordinate     = $points ? gzcompress(json_encode(explode('|', $points), 9)) : null; //路线坐标及坐标间距离信息
        $marathon_img   = [];
        $_FILES['routeimg']['error'] == 0 && $marathon_img['route_img'] = $this->load('qiniu')->uploadQiNiuImg('routeimg', 'marathon_route'.md5(time().$title));
        $_FILES['titleimg']['error'] == 0 && $marathon_img['title_img'] = $this->load('qiniu')->uploadQiNiuImg('titleimg', 'marathon_intru'.md5(time().$title));
        $_FILES['zsimg']['error'] == 0 && $marathon_img['zs_img'] = $this->load('qiniu')->uploadQiNiuImg('titleimg', 'marathon_zs'.md5(time().$title));
        !empty($marathon_img) && $marathon_img = json_encode($marathon_img);
        $status         = common::request('status', 'P');
        $add_time       = empty($marathonId) ? time() : null;
        $goods_id       = common::request('actGoodsId', 'P');
        $prompt_rule    = '';
        $charge         = 0;
        
        if ($goods_id) {
            $actGoods       = explode(',', $goods_id);
            //获取报名费用
            $goodsInfo      = $this->load('goods')->getGoodsById($actGoods[0]);

            $charge         = $goodsInfo['price'];
        }
        
        if ($ruleMiletype) {
            $tRule = explode(',', $ruleMiletype);
            
            foreach ($tRule as $rule) {
                $key = [];
                if (preg_match('/\d+(\.\d+)?/', $rule, $key)) {
                    $prompt_rule['mileage'][$key[0]] = $rule;
                }
            }
        }
        
        if ($ruleRanktype) {
            $tRule = explode(',', $ruleRanktype);
            
            foreach ($tRule as $rule) {
                $key = [];
                if (preg_match('/\d+/', $rule, $key)) {
                    $prompt_rule['rank'][$key[0]] = $rule;
                }
            } 
        }
        
        if ($ruleTimetype) {
            $tRule = explode(',', $ruleTimetype);
            
            foreach ($tRule as $rule) {
                $key = [];
                if (preg_match('/\d+/', $rule, $key)) {
                    $prompt_rule['elapsedtime'][$key[0]] = $rule;
                }
            } 
        }
        
        $prompt_rule = json_encode($prompt_rule);
        
        $rowValue       = compact('title', 'introduce', 'charge', 'copycontent', 'prompt_rule', 'total_mileage', 'start_time', 'end_time', 'mapattr', 'routeattr', 'coordinate', 'marathon_img', 'status', 'initial_joins', 'add_time', 'goods_id');
        !$marathonId && $rowValue = array_filter($rowValue); //新加活动去除空值
        
        //删除编辑时路径和图片空值
        if (empty($rowValue['coordinate'])){
            unset($rowValue['coordinate']);
        }
        
        if (empty($rowValue['marathon_img'])) {
            unset($rowValue['marathon_img']);  
        }

        $ret            = $marathonId 
                ? $this->db->updateRowTable('r_activity_marathon',array_merge($rowValue,['id' => $marathonId])) 
                : $this->db->insertRowTable('r_activity_marathon',$rowValue);  //插入或者更新
        
        if ($ret) {
            if ($marathonId) {
                //更新活动缓存信息
                $hashKey = REDIS_PREFIX . 'Marathon_Activity_' . $marathonId;
                $field   = 'marathon_' . $marathonId;
                $dbData  = [];
                
                if ($this->redis->hExists($hashKey, $field)) {
                    $dbData = $this->db->getRowTable('r_activity_marathon', [], 'id=' . $marathonId);
                    $dbData['coordinate'] = gzuncompress($dbData['coordinate']);
                    $this->redis->hSet($hashKey, $field, gzcompress(json_encode($dbData), 9));
                }

                if ($dbData['display'] == 1) {
                    $cacheKey = REDIS_PREFIX . 'Marathon_display';
                    
                    if ($this->redis->exists($cacheKey)) {
                        $cData = [];
                        $cData['url'] = "http://" . $this->config['host'] . '/marathonWeb/marathonIndex/?m_id=' . $dbData['id'];
                        $cData['start_time'] = $dbData['start_time'];
                        $cData['end_time'] = $dbData['end_time'];
                        $cData['status'] = $dbData['status'];
                        $cData['id'] = $dbData['id'];
                        $this->redis->set($cacheKey, json_encode($cData));
                        $this->redis->expire($cacheKey, $cData['end_time'] - time());
                    }
                }
                
                echo "更新成功，&nbsp;&nbsp;&nbsp;<a href='?c=actMarathon&a=marathoninfo&m_id={$marathonId}'>查看活动详情</a>";
            } else {
                echo "添加成功，&nbsp;&nbsp;&nbsp;<a href='?c=actMarathon&a=marathoninfo&m_id={$ret}'>查看活动详情</a>";
            }
            exit;
        } else {
            echo "操作失败&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href='".$_SERVER['HTTP_REFERER']."'>回到上一页</a>";
            exit;
        }
        
    }
    
    /**
     * 马拉松活动列表
     */
    public function domarathonList() {
        $p = common::request('p', 'G', 1);
        $p = intval($p);

        //分页
        require FILE . 'lib/page.class.php';
        $listNum = 10;
        $num = $this->db->getCol('select count(1)  from r_activity_marathon');
        $marathonList = $this->db->getAll(
            "select id,title,status,start_time,end_time,charge,total_mileage,display from r_activity_marathon order by id DESC limit " . ($p - 1) * $listNum . ',' . $listNum
        );

        $page = new Page($num['0'], $listNum);
        $pageStr = $page->show();
        $this->view->assign('pageStr', $pageStr);
        $this->view->assign('marathonList', $marathonList);
        $this->view->assign('hosts', "http://".$this->config['host']);
        $this->view->display('marathonlist');
    }
    
    /**
     * 修改app活动入口展示条目
     */
    public function dochangeDisplay() {
        $id = common::request('id', 'P');
        $op = common::request('operate', 'P');
        $retJson = ['code' => 1, 'msg' => '操作失败请稍后再试'];
        
        if ($op == 'set') {
            $ret = $this->db->update(
                'update r_activity_marathon set display=0 where display=1'
            );

            if ($ret !== false) {
                $ret = $this->db->updateRowTable('r_activity_marathon', ['id' => $id, 'display' => 1]);

                if ($ret) {
                    $cacheKey = REDIS_PREFIX . 'Marathon_display';

                    if ($this->redis->exists($cacheKey)) {
                        $rowData  = $this->db->getRowTable('r_activity_marathon', ['id', 'status', 'start_time', 'end_time'], 'id=' . $id);
                        $rowData['url'] = "http://" . $this->config['host'] . '/marathonWeb/marathonIndex/?m_id=' . $rowData['id'];
                        $this->redis->set($cacheKey, json_encode($rowData));
                        $this->redis->expire($cacheKey, $rowData['end_time'] - time());
                    }
                    
                    $retJson = ['code' => 0, 'msg' => '操作成功'];
                }
            }
        } else if ($op == 'cancel') {
            $ret = $this->db->updateRowTable('r_activity_marathon', ['id' => $id, 'display' => 0]);
            if ($ret !== false) {
                $cacheKey = REDIS_PREFIX . 'Marathon_display';
                
                if ($this->redis->exists($cacheKey)) {
                    $this->redis->expire($cacheKey, -1);
                }
                
                $retJson = ['code' => 0, 'msg' => '操作成功'];
            }
        } else {
            $retJson = ['code' => 2, 'msg' => '未知操作'];
        }
        
        exit(json_encode($retJson));
    }
}

